<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加订单</title>
    <link rel="stylesheet" type="text/css" href="/static/jquery-easyui-1.5.5.4/themes/metro/easyui.css"/>
    <link rel="stylesheet" type="text/css" href="/static/jquery-easyui-1.5.5.4/themes/icon.css"/>
    <script type="text/javascript" src="/static/jquery-easyui-1.5.5.4/jquery.min.js"></script>
    <script type="text/javascript" src="/static/jquery-easyui-1.5.5.4/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/static/jquery-easyui-1.5.5.4/locale/easyui-lang-zh_CN.js"></script>
</head>
<script>
    function openSaleListGoodsAddDialog() {
        $("#dlg").dialog("open").dialog("setTitle", "订单商品选择");
        $("#tree").tree({
            url: '/admin/goodsType/loadTreeInfo',
            onBeforeLoad: function () {
            },
            onLoadSuccess: function () {
                var rootNode = $("#tree").tree("getRoot");
                $("#tree").tree("expand", rootNode.target);
            },
            onClick: function (node) {
                $("#dg2").datagrid('load', {
                    "type.id": node.id
                });
            }
        });
    }

    function formatLastSellingPrice(val, row) {
        return "€" + val;
    }

    function formatSellingPrice(val, row) {
        return "€" + val;
    }

    function defaultPayNumer(val, row) {
        return 1;
    }

    function resetValue() {

    }


    var editIndex = undefined;        //选择商品删除
    var goodsData = {};        //选择的商品列表
    function endEditing() {           //正在编辑的row
        if (editIndex == undefined) {
            return true
        }
        if ($('#dg1').datagrid('validateRow', editIndex)) {
            $('#dg1').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }

    function deleteBtn(val, rowdata, rowIndex) {
        if (rowdata.id == undefined) {
            return "";
        }
        return "<input type='button' value='删除' onClick=\"deleteGoods(" + rowdata.id + ", " + rowIndex + ")\" >";
    }


    function deleteGoods(id, index) {
        if (editIndex == undefined) {
            return
        }
        $('#dg1').datagrid('cancelEdit', editIndex)
            .datagrid('deleteRow', editIndex);
        editIndex = undefined;
    }

    function removeit() {
        if (editIndex == undefined) {
            return
        }
        $('#dg1').datagrid('cancelEdit', editIndex)
            .datagrid('deleteRow', editIndex);
        console.log(editIndex);
        console.log(goodsData.rows);
        goodsData.rows.splice(editIndex, 0);
        console.log(goodsData.rows);
        updateGoodsData();

        editIndex = undefined;
    }


    function getGoodsData() {
        $('#dg1').datagrid({
            data: goodsData,
            columns: [[
                {field: 'code', title: '商品编码', width: 100, align: 'center'},
                {field: 'name', title: '商品名称', width: 100, align: 'center'},
                {field: 'model', title: '商品型号', width: 100, align: 'center'},
                {field: 'unit', title: '单位', width: 100, align: 'center'},
                {field: 'sellingPrice', title: '销售单价', width: 100, align: 'center', formatter: formatLastSellingPrice},
                {field: 'purchasingPrice', title: '成本均价', width: 100, align: 'center', formatter: formatSellingPrice},
                {field: 'payNumber', title: '购买数量', align: 'center', editor: {type: 'numberbox'}}
            ]],
            onClickRow: onClickRow,
            showFooter: true,
            singleSelect: true,
            onEndEdit: onEndEdit
        });
        $("#dlg").dialog("close");
    }


    function onClickRow(index, field) {
        var ed = $('#dg1').datagrid('getEditor', {index: index, field: "payNumber"});
        console.log($(this));
        if (ed) {

            $(ed.target).numberbox({
                onChange: function () {
                    console.log("232323");
                }
            });
        }
        console.log(endEditing());
        if (editIndex != index) {
            if (endEditing()) {
                $('#dg1').datagrid('selectRow', index)
                    .datagrid('beginEdit', index);
                var ed = $('#dg1').datagrid('getEditor', {index: index, field: "payNumber"});
                if (ed) {

                    $(ed.target).numberbox({
                        onChange: function () {

                        }
                    });
                }
                editIndex = index;
            } else {
                setTimeout(function () {
                    $('#dg1').datagrid('selectRow', editIndex);
                }, 0);
            }
        }
    }

    function onEndEdit(index, row) {
        var ed = $(this).datagrid('getEditor', {
            index: index,
            field: 'payNumber'
        });
        if (ed) {
            $(ed.target).numberbox({
                onChange: function () {
                    console.log("232323");
                }
            });
        }
        //row.productname = $(ed.target).combobox('getText');
    }

    function updateGoodsData() {
        var total = 0;
        var totalPurchasingPrice = 0;
        for (var j = 0, len = goodsData.rows.length; j < len; j++) {
            total += goodsData.rows[j]["sellingPrice"];
            totalPurchasingPrice += goodsData.rows[j]["purchasingPrice"];
        }
        var footer = [{"unit": "总价:", "sellingPrice": total, "purchasingPrice": totalPurchasingPrice}];
        goodsData.footer = footer;
        getGoodsData();
    }

    function ChooseDialog() {
        var selectdRows = $("#dg2").datagrid("getSelections");

        if (selectdRows.length == 0) {
            $.messager.alert("系统提示", "请选择数据");
            return;
        }
        var total = 0;
        var totalPurchasingPrice = 0;
        for (var j = 0, len = selectdRows.length; j < len; j++) {
            selectdRows[j]["payNumber"] = 1;
            total += selectdRows[j]["sellingPrice"];
            totalPurchasingPrice += selectdRows[j]["purchasingPrice"];
        }
        var footer = [{"unit": "总价:", "sellingPrice": total, "purchasingPrice": totalPurchasingPrice}];
        goodsData.rows = selectdRows;
        goodsData.footer = footer;
        getGoodsData();
    }

   function openGoodsChooseDialog() {
            $("#saveAddAddNextButton").show();
            var selectedRows = $("#dg2").datagrid("getSelections");
            if (selectedRows.length != 1) {
                $.messager.alert("系统提示", "请选择一个商品！");
                return;
            }
            var row = selectedRows[0];
            $("#dlg2").dialog("open").dialog("setTitle", "选择商品");
            $("#fm2").form("load", row);
            $("#sellingPrice").val("€" + row.sellingPrice);
            $("#sellingPrice1").numberbox("setValue", row.sellingPrice);
            $("#action").val("add");
            $("#goodsNum").focus();
        }

    $(document).ready(function () {
    });

    function submitForm() {

       $('#orderGoodsList').val(goodsData.rows);
        $('#ff').form('submit', {
            url:"/admin/order/save",
            queryParams: {goodsStr:JSON.stringify(goodsData.rows)},
            onSubmit: function () {
                return $(this).form('enableValidation').form('validate');
            },
            success: function () {

            }
        });
    }

    function clearForm() {
        $('#ff').form('clear');
    }

   function saveGoods(type) {
            var action = $("#action").val();
            if (!$("#fm4").form("validate")) {
                return;
            }
            if (action == "add") {
                var selectedRows = $("#dg2").datagrid("getSelections");
                var row = selectedRows[0];
                var sellingPrice = $("#price").numberbox("getValue");
                var goodsNum = $("#goodsNum").numberbox("getValue");
                var total = sellingPrice * goodsNum;
                $("#dg").datagrid("appendRow", {
                    code: row.code,
                    name: row.name,
                    model: row.model,
                    unit: row.unit,
                    // price: price,
                    goodsNum: goodsNum,
                    total: total,
                    typeId: row.type.id,
                    goodsId: row.id,
                    inventoryQuantity: row.inventoryQuantity,
                    sellingPrice: row.sellingPrice
                });
            } else if (action == "modify") {
                var rowIndex = $("#rowIndex").val();
                var selectedRows = $("#dg").datagrid("getSelections");
                var row = selectedRows[0];
                var sellingPrice = $("#sellingPrice").numberbox("getValue");
                var goodsNum = $("#goodsNum").numberbox("getValue");
                var total = sellingPrice * goodsNum;
                $("#dg").datagrid("updateRow", {
                    index: rowIndex,
                    row: {
                        code: row.code,
                        name: row.name,
                        model: row.model,
                        unit: row.unit,
                        // price: sellingPrice,
                        goodsNum: goodsNum,
                        total: total,
                        typeId: row.typeId,
                        goodsId: row.id,
                        inventoryQuantity: row.inventoryQuantity,
                        sellingPrice: row.sellingPrice
                    }
                });
            }
            setSaleListAmount();
            if (type == 1) {
                closeGoodsDialog();
            }
            closeGoodsChooseDialog();
        }

        function setSaleListAmount() {
            var rows = $("#dg").datagrid("getRows");
            var amount = 0;
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                amount += row.total;
            }
            $("#amountPayable").val(amount.toFixed(2));
            $("#amountPaid").val(amount.toFixed(2));
        }

         function closeGoodsDialog() {
            $('#s_codeOrName').val('');
            $("#dlg").dialog("close");
         }

          function closeGoodsChooseDialog() {
            resetValue();
            $("#dlg2").dialog("close");
           }

           function resetValue() {
            $("#sellingPrice").numberbox("setValue", "");
            $("#goodsNum").numberbox("setValue", "");
           }

           function searchGoods() {
                $("#dg2").datagrid('load', {
                    "codeOrName": $("#s_codeOrName").val()
                });
            }


           $(document).ready(function () {
            $("#dg").datagrid({
                onDblClickRow: function (index, row) {
                    $("#saveAddAddNextButton").hide();
                    $("#dlg2").dialog("open").dialog("setTitle", "修改销售单商品");
                    $("#fm2").form("load", row);
                    $("#sellingPrice").val("€" + row.sellingPrice);
                    $("#sellingPrice").numberbox("setValue", row.sellingPrice);
                    $("#goodsNum").numberbox("setValue", row.goodsNum);
                    $("#action").val("modify");
                    $("#goodsNum").focus();
                    $("#rowIndex").val($("#dg").datagrid("getRowIndex", row));
                }
            });

            $("#dg2").datagrid({
                onDblClickRow: function (index, row) {
                    $("#saveAddAddNextButton").show();
                    $("#dlg2").dialog("open").dialog("setTitle", "选择商品");
                    $("#fm2").form("load", row);
                    $("#sellingPrice").val("€" + row.sellingPrice);
                    $("#sellingPrice").numberbox("setValue", row.sellingPrice);
                    $("#action").val("add");
                    $("#goodsNum").focus();
                }
            });
        });

         function deleteSaleListGoods(){
               var selectedRows = $("#dg").datagrid("getSelections");
               console.log(selectedRows.length);
               if(selectedRows.length !=1){
                   $.messager.alert("系统提示", "请选择一条要删除的商品");
                   return;
               }

               $.messager.confirm("系统提示", "确认删除该商品么？", function(r){
                    if(r){
                        $("#dg").datagrid("deleteRow", $("#dg").datagrid("getRowIndex", selectedRows[0]));
                        setSaleListAmount();
                    }
               });
         }

         function openSaleListGoodsModifyDialog() {
            $("#saveAddAddNextButton").hide();
            var selectedRows = $("#dg").datagrid("getSelections");
            if (selectedRows.length != 1) {
                $.messager.alert("系统提示", "请选择一个商品！");
                return;
            }
            var row = selectedRows[0];
            $("#dlg2").dialog("open").dialog("setTitle", "修改销售单商品");
            $("#fm2").form("load", row);
            $("#sellingPrice").val("€" + row.sellingPrice);
            $("#sellingPrice").numberbox("setValue", row.sellingPrice);
            $("#goodsNum").numberbox("setValue", row.goodsNum);
            $("#action").val("modify");
            $("#goodsNum").focus();
            $("#rowIndex").val($("#dg").datagrid("getRowIndex", row));
        }

        function saveSaleGoods() {
            $("#saleNumber").val($("#dh").text());                //单号
            $("#goodsJson").val(JSON.stringify($("#dg").datagrid("getData").rows));
            //$('#orderGoodsList').val(goodsData.rows);

            $("#fm").form("submit", {
                url: "/admin/order/save",
                //queryParams: {goodsStr:JSON.stringify(goodsData.rows)},
                onSubmit: function () {
                    if ($("#dg").datagrid("getRows").length == 0) {
                        $.messager.alert("系统提示", "请添加销售商品！");
                        return false;
                    }
                    if (!$(this).form("validate")) {
                        return false;
                    }
                    if (isNaN($("#customerId").combobox("getValue"))) {
                        $.messager.alert("系统提示", "请选择客户！");
                        return false;
                    }
                    return true;
                },
                success: function (result) {
                    var result = eval('(' + result + ')');
                    if (result.success) {
                        alert("保存成功！");
                        window.location.reload();
                    } else {
                        $.messager.alert("系统提示", result.errorInfo);
                    }
                }
            });
        }


</script>
<body  class="easyui-layout">
<div data-options="region:'north'" style="height: 135px;padding: 10px;border: 0px;padding-top: 20px">
    <fieldset style="border-color: #E7F0FF">
        <form id="fm" method="post">
            <table cellspacing="8px">
                <tr>
                    <td>
                        客&nbsp;户：<input class="easyui-combobox" id="customerId" name="customerId" style="width: 200px"
                                        required="true"
                                        data-options="required:true,panelHeight:'auto',valueField:'id',textField:'name',url:'/admin/customer/comboList'"/>
                    </td>
                    <td>
                        &nbsp;&nbsp;&nbsp;&nbsp;应付金额：<input type="text" id="amountPayable" name="orderAmount"
                                                            class="easyui-validatebox" required="true"
                                                            readonly="readonly" size="10"/>
                    </td>
                    <td>
                        &nbsp;&nbsp;&nbsp;&nbsp;实付金额：<input type="text" id="amountPaid" name="realAmount"
                                                            class="easyui-validatebox" required="true" size="10"/>
                    </td>
                    <td>
                        &nbsp;&nbsp;&nbsp;&nbsp;电话：<input type="text" id="saleDate" name="mobile"
                                                          class="easyui-textbox" required="true" size="18"/>
                    </td>
                    <td>
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
                        备&nbsp;注：<input type="text" id="remarks" name="remarks" size="78"/>
                    </td>
                    <td></td>
                    <td>
                        <input type="hidden" id="saleNumber" name="saleNumber"/>
                        <input type="hidden" id="goodsJson" name="goodsJson"/>
                        &nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:saveSaleGoods()" class="easyui-linkbutton"
                                                   iconCls="icon-ok">保存</a>
                    </td>
                </tr>
            </table>
        </form>
    </fieldset>
</div>
<div data-options="region:'center'" style="padding: 10px;border: 1px">
    <table id="dg" class="easyui-datagrid" style="height：1200px"
           fitColumns="true" rownumbers="true" singleSelect="true"
           fit="true" toolbar="#tb">
        <thead>
        <th field="code" width="30" align="center">商品编码</th>
        <th field="name" width="150" align="center">商品名称</th>
        <th field="model" width="50" align="center">型号</th>
        <th field="sku" width="50" align="center">单位</th>
        <th field="sellingPrice" width="50" align="center">单价</th>
        <th field="goodsNum" width="50" align="center">数量</th>
        <th field="total" width="50" align="right">总金额</th>
        </thead>
    </table>

    <div id="tb">
        <div style="padding: 2px">
            <a href="javascript:openSaleListGoodsAddDialog()" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a>
            <a href="javascript:openSaleListGoodsModifyDialog()" class="easyui-linkbutton" iconCls="icon-edit"
               plain="true">修改</a>
            <a href="javascript:deleteSaleListGoods()" class="easyui-linkbutton" iconCls="icon-remove"
               plain="true">删除</a>
        </div>
    </div>
</div>

<div id="dlg" class="easyui-dialog" style="width: 800px;height: 460px;"
     closed="true" data-options="onClose:function(){$('#s_codeOrName').val('');}">
    <div class="easyui-layout" style="width: 100%;height: 100%">
        <div region="north" style="height: 50px">
            <div style="padding-top: 8px;padding-left: 40px">
                &nbsp;商品编码或者名称：&nbsp;<input type="text" id="s_codeOrName" size="20"
                                            onkeydown="if(event.keyCode==13) searchGoods()"/>
                <a href="javascript:searchGoods()" class="easyui-linkbutton" iconCls="icon-search" plain="true">搜索</a>
            </div>
        </div>

        <div data-options="region:'west',collapsible:false" style="width: 200px" title="商品类别" split=true>
            <ul id="tree" class="easyui-tree" style="padding: 10px"></ul>
            <div style="position: absolute;bottom: 10px;left: 15px"></div>
        </div>

        <div data-options="region:'center'">
            <table id="dg2" title="商品管理" class="easyui-datagrid"
                   fitColumns="true" pagination="true" rownumbers="true" singleSelect="true"
                   url="/admin/goods/list" fit="true" toolbar="#tb2">
                <thead>
                <th field="id" width="30" hidden="true" align="center">编号</th>
                <th field="code" width="50" align="center">商品编码</th>
                <th field="name" width="150" align="left">商品名称</th>
                <th field="model" width="50" align="center">商品型号</th>
                <th field="unit" width="50" align="center">单位</th>
                <th field="sellingPrice" width="50" align="right" formatter="formatLastSellingPrice">销售单价</th>
                <th field="purchasingPrice" width="50" align="right" formatter="formatSellingPrice">成本均价</th>
                <th field="inventoryQuantity" width="50" align="center">库存数量</th>
                </thead>
            </table>
            <div id="tb2">
                <div>
                    <a href="javascript:openGoodsChooseDialog()" class="easyui-linkbutton" iconCls="icon-ok" plain="true">选择</a>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="dlg2" class="easyui-dialog" style="width: 600px;height: 400px;padding: 5px 5px"
     closed="true" buttons="#dlg-buttons2" data-options="onClose:function(){resetValue()}">
    <fieldset style="border-color: #E7F0FF">
        <legend>商品信息</legend>
        <form id="fm2" method="post">
            <table cellspacing="8px">
                <tr>
                    <td>商品编号：</td>
                    <td>
                        <input type="text" id="code" name="code" readonly="readonly" size="10"/>
                    </td>
                    <td width="60">商品名称：</td>
                    <td>
                        <input type="text" id="name" name="name" readonly="readonly" size="10"/>
                    </td>
                </tr>
                <tr>
                    <td>商品型号：</td>
                    <td>
                        <input type="text" id="model" name="model" readonly="readonly" size="10"/>
                    </td>
                    <td>商品单位：</td>
                    <td>
                        <input type="text" id="unit" name="unit" readonly="readonly" size="10"/>
                    </td>
                </tr>
                <tr>
                    <td>销售单价：</td>
                    <td>
                        <input type="text" id="sellingPrice" name="sellingPrice" readonly="readonly" size="10"/>
                    </td>
                    <td>当年库存：</td>
                    <td>
                        <input type="text" id="inventoryQuantity" name="inventoryQuantity" readonly="readonly"
                               size="10"/>
                    </td>
                </tr>
            </table>
        </form>
    </fieldset>
    <div style="padding-left: 12px;padding-top: 10px">
        <form id="fm4" method="post">
            <table cellspacing="8px">
                <tr>
                    <td align="right">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;单价：</td>
                    <td>
                        <input type="hidden" id="action"/>
                        <input type="hidden" id="rowIndex"/>
                        <input type="text" id="sellingPrice1" name="sellingPrice" class="easyui-numberbox"
                               data-options="min:0,precision:2" required="true" size="10"/>
                    </td>
                    <td align="right" width="60">数量：</td>
                    <td>
                        <input type="text" id="goodsNum" name="goodsNum" class="easyui-numberbox" data-options="min:1"
                               required="true" size="10"/>
                    </td>
                </tr>
            </table>
        </form>
    </div>
</div>


<div id="dlg-buttons2">
    <a id="saveAddAddNextButton" href="javascript:saveGoods(2)" class="easyui-linkbutton"
       iconCls="icon-ok">保存并新增下一商品</a>
    <a href="javascript:saveGoods(1)" class="easyui-linkbutton" iconCls="icon-ok">保存</a>
    <a href="javascript:closeGoodsChooseDialog()" class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
</div>

</body>
</html>